package dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import pojos.Score;
import comm.Pagination;

public class ScoreDaoHib extends HibernateDaoSupport implements ScoreDao {

	@Override
	public Score getById(Integer id) {
		String hql = "from Score where id = ?";
		return (Score) getHibernateTemplate().find(hql).get(0);
	}

	@Override
	public void saveOrUpdate(Score score) {
		getHibernateTemplate().saveOrUpdate(score);
	}

	@Override
	public void delete(Score score) {
		getHibernateTemplate().delete(score);
	}

	@Override
	public void deleteById(final Integer id) {
		getHibernateTemplate().execute(new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session s)
					throws HibernateException, SQLException {
				String hql = "delete Score where id = ?";
				Query query = s.createQuery(hql);
				query.setInteger(0, id);
				query.executeUpdate();
				return null;
			}
		});
	}

	@Override
	public List<Score> findByStudentId(final Integer stuId, final Pagination pagination) {
		return getHibernateTemplate().execute(new HibernateCallback<List<Score>>() {

			@SuppressWarnings("unchecked")
			@Override
			public List<Score> doInHibernate(Session s)
					throws HibernateException, SQLException {
				String hql = "from Score where student.id = ?";
				Query query = s.createQuery(hql);
				query.setInteger(0, stuId);
				query.setFirstResult(pagination.getStart())
				.setMaxResults(pagination.getSize());
				pagination.setTotalRecord((int)getCount(stuId));
				return query.list();
			}

			private long getCount(Integer stuId) {
				String hql = "select count(*) from Score where student.id = ?";
				return (Long)getHibernateTemplate().find(hql,stuId).get(0);
				
			}
		});
	}

	@Override
	public List<Score> findByExamId(final Integer examId, final Pagination pagination) {
		return getHibernateTemplate().execute(new HibernateCallback<List<Score>>() {

			@SuppressWarnings("unchecked")
			@Override
			public List<Score> doInHibernate(Session s)
					throws HibernateException, SQLException {
				String hql = "from Score where exam.id = ?";
				Query query = s.createQuery(hql);
				query.setInteger(0,examId);
				query.setFirstResult(pagination.getStart())
				.setMaxResults(pagination.getSize());
				pagination.setTotalRecord((int)getCount(examId));
				return query.list();
			}

			private long getCount(Integer examId) {
				String hql = "select count(*) from Score where exam.id = ?";
				return (Long)getHibernateTemplate().find(hql,examId).get(0);
			}
		});
	}

}
